// 引入日志打印
import {log} from "@/utils/utils.ts";
// 系统定义前缀
import {storagePrefix, storageExpire} from "@/config/globalConfig.ts";

interface StorageItem {
    time: number,
    data: any
}

// storage存储对象
class StorageUtil {
    constructor(private prefix: string = storagePrefix) {
        this.prefix = prefix;
    }
    // 确认是否过期
    isExpire(time: number) {
        if(time === -1) return false;
        return this.getNow() >= time;
    }
    // 获取当前时间戳
    getNow(): number {
        return (new Date()).getTime();
    }
    // 修改前缀
    changePrefix(prefix: string) {
        this.prefix = prefix;
    }

    /**
     * 获取storage存储的内容
     * @param key
     */
    get(key: string) {
        try {
            const json: string = window.localStorage.getItem(key) as string;
            const obj: StorageItem = JSON.parse(json);
            if(obj && !this.isExpire(obj.time)) return obj.data;
            else {
                log(key + "已过期");
                this.clearItem(key);
                return null;
            }
        } catch (e) {
            log(e, "获取缓存：" + key + " 失败");
            return null
        }
    }

    /**
     * 获取系统定义的存储内容
     * @param key 键
     */
    getDefault(key: string) {
        return this.get(this.prefix + key);
    }
    /**
     * 存储对象
     * @param key 键
     * @param value 值
     * @param expire 过期时间
     */
    set(key: string, value: any, expire: number = -1) {
        try {
            const json: StorageItem = {
                time: expire === -1? -1 : ((new Date()).getTime() + expire),
                data: value
            }
            window.localStorage.setItem(key, JSON.stringify(json));
            return true;
        } catch (e) {
            log(e, "缓存存储：" + key + " 失败");
            return false;
        }
    }

    /**
     * 系统默认存储方法
     * @param key
     * @param value
     */
    setDefault(key: string, value: any) {
        return this.set(this.prefix + key, value, storageExpire);
    }
    /**
     * 清除storage相应的项
     * @param key 键
     */
    clearItem(key: string) {
        try {
            window.localStorage.removeItem(key);
            return true;
        } catch (e) {
            log(e, "清除缓存：" + key + " 失败");
            return false;
        }
    }
    clearItemDefault(key: string) {
        return this.clearItem(this.prefix + key);
    }
    /**
     * 清除所有缓存，一般不经常使用
     */
    clearAll() {
        try {
            window.localStorage.clear();
            return true;
        } catch (e) {
            log("清除所有缓存失效");
            return false;
        }
    }
}

export default new StorageUtil();
